package com.sitech.ibnms.c3p.command.sql;

import com.sitech.ibnms.c3p.domain.ResourceAccount;
import com.sitech.ismp.workflow.util.DES3;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.stereotype.Component;

/**
 * Created by leo on 16/2/16.
 */
@Component
public class SQLExecutorImpl implements SQLExecutor {

    @Override
    public <T> T execute(final ResourceAccount resourceAccount, final ConnectionCallback<T> action) {
        SingleConnectionDataSource dataSource = null;
        try {
            dataSource = dataSource(resourceAccount);
            return new JdbcTemplate(dataSource).execute(action);
        } finally {
            if (dataSource != null) dataSource.destroy();
        }
    }

    private SingleConnectionDataSource dataSource(final ResourceAccount resourceAccount) {
        return new SingleConnectionDataSource(resourceAccount.getDbUrl(), resourceAccount.getUserName(), DES3.decrypt(resourceAccount.getPassword()), true);
    }
}
